layui.define(['jquery', 'form', 'select2', 'laydate'], function (exports) {
	var $ = layui.jquery
	var $itemP = $(
			'<div class="filter-item"><div class="advance-group filter-fields"><select name="fields" placeholder="请选择查询字段" lay-ignore></select></div><div class="advance-group filter-operator"><select name="operator" placeholder="请选择条件" lay-ignore></select></div><div class="advance-group filter-value"><input type="text" name="value" placeholder="请先选择查询字段" disabled class="css_dindex layui-input" /></div><div class="advance-group filter-btn"><button class="layui-btn filter-item_ope" advance-type="itemAdd" title="添加条件"><i class="layui-icon layui-icon-addition"></i></button><button class="layui-btn filter-item_ope" advance-type="itemDel" title="删除条件"><i class="layui-icon layui-icon-subtraction"></i></button></div></div>'
		),
		$groupBoxP = $(
			'<div class="filter-groupBox"><div class="filter-group"></div><div class="filter-andor"><select name="andor" lay-verify="required"><option value="or">OR</option><option value="and">AND</option></select></div><i class="layui-icon layui-icon-close" advance-type="groupDel"></i></div>'
		),
		$valueInputP = $('<input type="text" name="value" placeholder="请输入查询值" class="css_dindex layui-input" />')
	$valueSelect2P = $('<select name="value" placeholder="请选择查询值" lay-ignore></select>')
	var obj = {
		initOptions: {
			/* layFilter: undefined, */
			fields: [],
			operator: [
				{ id: '等于', text: '等于' },
				{ id: '不等于', text: '不等于' },
				{ id: '大于', text: '大于' },
				{ id: '大于等于', text: '大于等于' },
				{ id: '小于', text: '小于' },
				{ id: '小于等于', text: '小于等于' },
				{ id: '包含', text: '包含' },
				{ id: '不包含', text: '不包含' }
			]
			/* andor: [
				{ id: 'and', text: 'AND' },
				{ id: 'or', text: 'OR' }
			] */
		},
		optionss: {}, //filterSel: options
		init: function (filterSel, _options) {
			if (!filterSel) return

			var _this = this

			var $advanceOut = $(filterSel),
				$container = $groupBoxP.clone(true).removeClass('filter-groupBox').addClass('advance-filter-container'), //最外层
				$list = $container.find('.filter-group').removeClass('filter-group').addClass('filter-list'),
				$addTop = $(
					'<div class="filter-add"><button class="layui-btn filter-item_ope" advance-type="itemAddTop" title="添加条件"><i class="layui-icon layui-icon-addition"></i>添加条件</button><button class="layui-btn filter-item_ope" advance-type="groupAddTop" title="添加条件组"><i class="layui-icon layui-icon-addition"></i>添加条件组</button></div>'
				)

			$container.find('[advance-type="groupDel"]').remove()
			$container.find('[name="andor"]').val('and') //最外层条件默认为 AND
			$advanceOut.append($container).append($addTop)

			_this.fieldsDataFormat(filterSel, $advanceOut, _options) //保存选项数据

			var defaultData = _this.optionss[filterSel]['defaultData']
			if (!defaultData) {
				//无默认值时
				var $item = _this.genItem(),
					$groupBoxs = _this.genGroupBox()
				$list.append($item).append($groupBoxs)
			}

			$advanceOut.on('click', '[advance-type]', function () {
				var type = $(this).attr('advance-type')
				!_this[type] || _this[type].call(this, filterSel, $advanceOut)
				return false
			})

			$advanceOut.on('change', '[name="fields"]', function () {
				//使用 change 为遍历默认值时 trigger('change') 让路
				var fieldsId = $(this).val()

				if (!fieldsId) return
				var $item = $(this).closest('.filter-item'),
					$operator = $item.find('[name="operator"]'),
					$filterValue = $item.find('[name="value"]').parent(),
					fieldsIdData = _this.optionss[filterSel]['fieldsData'][fieldsId],
					curOperator = fieldsIdData['operator'],
					operatorDefaul = fieldsIdData['operatorDefaul']

				layui.select2.open($item.find($operator), {
					placeholder: '请选择条件',
					allowClear: false,
					minimumResultsForSearch: 'Infinity',
					initData: !curOperator || curOperator.length === 0 ? _this.initOptions['operator'] : curOperator
				})
				!operatorDefaul || $operator.val(operatorDefaul).trigger('change') //选中默认条件

				if (fieldsIdData['isSelect']) {
					//如果 value 是 下拉框形式
					var $curValueSelect2 = $valueSelect2P.clone()
					$filterValue.html('').append($curValueSelect2)
					layui.select2.open($curValueSelect2, fieldsIdData['select2'] || {}) //使用提供的 select2 参数
				} else {
					var $curValueInput = $valueInputP.clone(),
						dateType = fieldsIdData['dateType'] || 'datetime'
					if (fieldsIdData['isDate']) {
						$curValueInput.attr('lay' + dateType, '')
						layui.laydate.render({
							elem: $curValueInput[0],
							type: dateType
						})
					}
					$filterValue.html('').append($curValueInput)
				}
			})

			_this.end(filterSel, $advanceOut)

			if (defaultData) {
				//遍历默认值
				_this.defaultDataLoad(filterSel, defaultData)
			}
		},
		fieldsDataFormat: function (filterSel, $advanceOut, _options) {
			var _this = this
			_this.optionss[filterSel] = _options
			if (!_options['fieldsData']) return
			_this.optionss[filterSel]['fields'] = []
			$.each(_options['fieldsData'], function (key, item) {
				_this.optionss[filterSel]['fields'].push({ id: key, text: item['text'] || '' })
			})
			_this.optionss[filterSel]['$advanceOut'] = $advanceOut
		},
		genItem: function () {
			// 生成 filter-item
			var $item = $itemP.clone()
			return $item
		},
		genGroupBox: function () {
			//生成 filter-groupBox
			var $groupBox = $groupBoxP.clone(true)
			$groupBox.find('.filter-group').append($itemP.clone()).append($itemP.clone())
			return $groupBox
		},
		itemAdd: function (filterSel) {
			//添加条件
			var $item = obj.genItem()
			$(this).closest('.filter-item').after($item)
			obj.end(filterSel, $item)
		},
		itemDel: function () {
			//删除条件
			$(this).closest('.filter-item').remove()
		},
		groupDel: function () {
			//删除条件组
			$(this).closest('.filter-groupBox').remove()
		},
		itemAddTop: function (filterSel, $advanceOut) {
			//顶层添加条件
			var $item = obj.genItem()
			$advanceOut.find('.filter-list').append($item)
			obj.end(filterSel, $item)
		},
		groupAddTop: function (filterSel, $advanceOut) {
			//顶层添加条件组
			$genGroupBox = obj.genGroupBox()
			$advanceOut.find('.filter-list').append($genGroupBox)
			obj.end(filterSel, $genGroupBox)
		},
		end: function (filterSel, $el) {
			// select2、select初始化
			var _this = this,
				$fields = $el.find('[name="fields"]'),
				$operator = $el.find('[name="operator"]')

			layui.select2.open($fields, {
				placeholder: '请选择查询字段',
				allowClear: false,
				initData: _this.optionss[filterSel].fields || initOptions['fields']
			})
			$fields.val(null).trigger('change') //fields 默认不选中

			layui.select2.open($operator, {
				placeholder: '请选择条件',
				allowClear: false,
				minimumResultsForSearch: 'Infinity', //不显示搜索框
				// initData: _this.optionss[filterSel].operator
				initData: []
			})

			/* layui.select2.open($el.find('[name="andor"]'), {
				placeholder: '请选择条件',
                allowClear: false,
                minimumResultsForSearch: 'Infinity',
				initData: _this.optionss[filterSel].andor
            }) */

			layui.form.render('select', _this.optionss[filterSel].layFilter)
		},
		getFilterData: function (filterSel, getValDisplay) {
			var $list = this.optionss[filterSel]['$advanceOut'].find('.filter-list'),
				filterData = {
					data: [],
					optionType: $list.find('~ .filter-andor [name="andor"]').val()
				}

			if (!filterData['optionType']) return false

			$list.find(' > .filter-item').each(function () {
				var $this = $(this),
					$value = $this.find('[name="value"]')
				curData = {
					Condition: $this.find('[name="fields"]').val(),
					ComputeSign: $this.find('[name="operator"]').val(),
					ConditionValue: $value.val()
				}

				if (!curData['Condition'] || !curData['ComputeSign'] || !curData['ConditionValue']) return //有无效值，不保存

				if (getValDisplay && $value.is('select')) {
					var selectData = $value.select2('data')[0]
					if (selectData) {
						curData['ValueDisplay'] = selectData['text']
					}
				}

				filterData['data'].push(curData)
			})

			$list.find(' > .filter-groupBox').each(function () {
				var $groupBox = $(this),
					groupData = {
						data: [],
						optionType: $groupBox.find('> .filter-andor [name="andor"]').val()
					}

				$groupBox.find('.filter-item').each(function () {
					var $item = $(this),
						$value = $item.find('[name="value"]')
					curData = {
						Condition: $item.find('[name="fields"]').val(),
						ComputeSign: $item.find('[name="operator"]').val(),
						ConditionValue: $value.val()
					}

					if (!curData['Condition'] || !curData['ComputeSign'] || !curData['ConditionValue']) return //有无效值，不保存

					if (getValDisplay && $value.is('select')) {
						var selectData = $value.select2('data')[0]
						if (selectData) {
							curData['ValueDisplay'] = selectData['text']
						}
					}

					groupData['data'].push(curData)
				})

				if (groupData['data'].length === 0) return
				filterData['data'].push(groupData)
			})

			return filterData
		},
		defaultDataLoad: function (filterSel, defaultData, _options) {
			if (!defaultData || !defaultData['optionType']) return //至少需要存在最外层 optionType
			var options = {
				valueHighlight: false,	//$value 高亮
			}
			!_options ||  $.extend(options, _options)
			var _this = this,
				$container = $(filterSel).find('.advance-filter-container'),
				$list = $container.find('.filter-list')
			
			// if(!_this.optionss[filterSel]['defaultData']) $list.html('')	//如果存在系统默认值 不清空
			$list.html('')
			
			if (defaultData['data'] && defaultData['data'].length > 0) {
				defaultData['data'].forEach(function (item) {
					if (item['optionType']) {
						//filter-group
						var $groupBox = $groupBoxP.clone(true),
							$group = $groupBox.find('.filter-group')
						$groupBox.find('[name="andor"]').val(item['optionType'])
						$list.append($groupBox)
						if (item['data'] && item['data'].length > 0) {
							item['data'].forEach(function (item) {
								appendItem($group, item)
							})
						}
					} else {
						appendItem($list, item)
					}
				})
			}

			$container.find('> .filter-andor [name="andor"]').val(defaultData['optionType'])

			layui.form.render('select', _this.optionss[filterSel].layFilter)

			function appendItem($group, item) {
				var $item = _this.genItem()
				_this.end(filterSel, $item)
				$group.append($item)
				$item.find('[name="fields"]').val(item['Condition']).trigger('change') //fields 选中默认条件
				$item.find('[name="operator"]').val(item['ComputeSign']).trigger('change') //fields 选中默认条件
				var $value = $item.find('[name="value"]')
				if ($value.is('select')) {
					layui.select2.open($value, {
						selected: [
							{
								defaultId: item['ConditionValue'],
								defaultValue: item['ValueDisplay']
							}
						]
					})
					!options['valueHighlight'] || cssFun($value.next().find('.select2-selection--single'))
				} else {
					$value.val(item['ConditionValue'])
					!options['valueHighlight'] || cssFun($value)
				}
			}

			function cssFun($elem) {
				$elem.addClass('isdefault')
				$elem.on('click', function (e) {
					$elem.removeClass('isdefault')
					$elem.off(e)
				})
			}
		},
		reset: function (filterSel) {
			var $advanceOut = $(filterSel)
			$advanceOut.html('')
			this.init(filterSel, this.optionss[filterSel])
		}
	}
	//输出接口
	exports('advance', obj)
})
